package com.walle.gatewayserver.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.walle.gatewayserver.utils.GetParamsUtil;
import com.walle.gatewayserver.utils.GetResponseBodyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Slf4j
@Component
public class ResponseFilter extends ZuulFilter {
	
	
	@Override
	public Object run() throws ZuulException {
		
		RequestContext ctx = RequestContext.getCurrentContext();
		
		
		HttpServletRequest request = ctx.getRequest();
		
		String uid = request.getHeader("uid");
		String token = request.getHeader("token");
		String sysType = request.getHeader("sysType");
		
		String body="";
		try {
			body = GetResponseBodyUtil.getResponseBody(ctx);
		} catch (IOException e) {
			log.error("======== 读取响应信息异常： url=[{}] uid=[{}] token=[{}] sysType=[{}] params=[{}] result=[{}] ",request.getRequestURL().toString(),uid,token,sysType,GetParamsUtil.getParams(ctx),e.getMessage());
		}
		
		ctx.setSendZuulResponse(true);
		ctx.setResponseStatusCode(200);
		if(!StringUtils.isEmpty(body)) {
			
			ctx.setResponseBody(body);
		}
		
		
		log.info("======== 访问请求： url=[{}] uid=[{}] token=[{}] sysType=[{}] params=[{}] result=[{}]",request.getRequestURL().toString(),uid,token,sysType,GetParamsUtil.getParams(ctx),body);
		return null;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public int filterOrder() {
		// TODO Auto-generated method stub
		return 3;
	}

	@Override
	public String filterType() {
		// TODO Auto-generated method stub
		return "post";
	}

}
